"""
认证相关路由
"""
import random
import string
from flask import Blueprint, render_template, request, redirect, url_for, flash, session
from flask_login import login_user, logout_user, current_user, login_required
from app.extensions import db
from app.models.user import User

auth_bp = Blueprint('auth', __name__)


def generate_captcha():
    """生成简单的验证码"""
    return ''.join(random.choices(string.digits, k=4))


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        captcha_input = request.form.get('captcha')
        captcha_session = session.get('captcha')
        
        if not captcha_input or captcha_input != captcha_session:
            flash('验证码错误')
            return render_template('auth/login.html')
        
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password):
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('main.dashboard'))
        else:
            flash('用户名或密码错误')
    
    # 生成新的验证码
    captcha = generate_captcha()
    session['captcha'] = captcha
    
    return render_template('auth/login.html', captcha=captcha)


@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))